package com.scalpel.web.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 网页工具
 * Created by scalpel on 2017/1/11.
 */
public class WebUtil {

    /**
     * 判断ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }

    /**
     * 设置下载文件的响应头和文件名
     *
     * @param fileName
     */
    public static void setDownHeader(String fileName){
        HttpServletRequest request = WebLocal.getRequest();
        HttpServletResponse response = WebLocal.getResponse();

        String userAgent = request.getHeader("User-Agent");
        try {
            fileName = encodeDownloadName(fileName, userAgent);
        } catch (Exception e) {
            fileName = "fileName";
        }
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        response.setContentType("application/octet-stream");
    }


    /**
     * 设置下载文件的编码，兼容大部分浏览器，不确保兼容所有
     * @param fileName 文件名
     * @param userAgent HTTP 请求的用户代理头的值
     * @return
     * @throws Exception
     */
    public static String encodeDownloadName(String fileName,String userAgent) throws Exception {
        //针对IE或者以IE为内核的浏览器：
        if (userAgent.toUpperCase().contains("MSIE")||userAgent.toUpperCase().contains("TRIDENT")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        }
//        fileName = StringUtils.deleteWhitespace(fileName);
        return fileName;
    }
}
